package com.anli1.interceptor;

import com.anli1.exception.BusinessException;
import com.anli1.tool.TokenEncryption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class MyInterceptor implements HandlerInterceptor {
  @Autowired
    TokenEncryption tokenEncryption;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      /*  HttpSession session = request.getSession();
        String token= (String) session.getAttribute("session_account");*/
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod=(HandlerMethod)handler;
        if(handlerMethod.getBean().getClass().getName().equals("springfox.documentation.swagger.web.ApiResourceController")){
            return  true;
        }

//判断如果请求的类是swagger的控制器，直接通行。

        if(tokenEncryption==null)
        {
            tokenEncryption=new TokenEncryption();
            /*
                key: "w7HqL+Jz3Kt0J3u6fYT3Ow=="
    iv: "77b07a672d57d64c"
    algorithm: AES
             */
            tokenEncryption.setKey("w7HqL+Jz3Kt0J3u6fYT3Ow==");
            tokenEncryption.setIv("77b07a672d57d64c");
            tokenEncryption.setAlgorithm("AES");
        }

        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            throw new BusinessException("用户错误");
        }
        for (Cookie cookie : cookies) {
            if ("username".equals(cookie.getName())) {
                String username = cookie.getValue();
              String userid  =tokenEncryption.retToken(username);
              String accountId = userid.replaceAll(".*accountId=(\\d+).*", "$1");
              RequestContextHolder.currentRequestAttributes().setAttribute("userId", accountId, RequestAttributes.SCOPE_REQUEST);

                return true;
            }
        }
        throw new BusinessException("用户错误");
    }
}
